package cn.richard.demo.xml.bean;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

import cn.hutool.core.io.resource.ClassPathResource;
import lombok.Data;
import lombok.experimental.Accessors;

@Data
@Accessors(chain = true)
@XmlRootElement(name = "Document")
@XmlAccessorType(XmlAccessType.FIELD)
public class PaymentBean391 {
	@XmlElement(name = "CstmrCdtTrfInitn")
	private CstmrCdtTrfInitn CstmrCdtTrfInitn;
	
	public static void main(String[] args) throws JAXBException {
		bean2xml();
		xml2bean();
	}

	private static void xml2bean() throws JAXBException {
		//获取上下文
		JAXBContext context = JAXBContext.newInstance(PaymentBean391.class);
		//Unmarshal 表示 XML->Java 的过程
		Unmarshaller unmarshaller = context.createUnmarshaller();
		//获取转换结果
		ClassPathResource classPathResource = new ClassPathResource("HK_DFT_PIU391_XMLv3_Sample_MASK.xml");
		PaymentBean391 xmlBean = (PaymentBean391) unmarshaller.unmarshal(classPathResource.getStream());
		System.out.println(xmlBean);
	}

	private static void bean2xml() throws JAXBException {
		InitgPty InitgPty = new InitgPty().setNm("HADSUND INTL TECH LTD");
		GrpHdr GrpHdr = new GrpHdr().setInitgPty(InitgPty).setMsgId("20170321D00000000").setCreDtTm("2017-07-08T11:11:11").setNbOfTxs(3);
		CstmrCdtTrfInitn CstmrCdtTrfInitn = new CstmrCdtTrfInitn().setGrpHdr(GrpHdr);
		PaymentBean391 xmlBean = new PaymentBean391().setCstmrCdtTrfInitn(CstmrCdtTrfInitn);
		
		//获取JAXB上下文对象
		JAXBContext context = JAXBContext.newInstance(PaymentBean391.class);
		//Marshal 表示 Java->XML 的过程
		Marshaller marshaller = context.createMarshaller();
		//格式化输出设置，不设置的话，得到的输出是单行紧凑的
		marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
		//转换输出结果
		try(ByteArrayOutputStream out = new ByteArrayOutputStream()){
			marshaller.marshal(xmlBean, out);
			System.out.println(out);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

@Data
@Accessors(chain = true)
@XmlAccessorType(XmlAccessType.FIELD)
class CstmrCdtTrfInitn {
	@XmlElement(name = "GrpHdr")
	private GrpHdr GrpHdr;
}
@Data
@Accessors(chain = true)
@XmlAccessorType(XmlAccessType.FIELD)
class GrpHdr {
	@XmlElement(name = "MsgId")
	private String MsgId;
	@XmlElement(name = "CreDtTm")
	private String CreDtTm;
	@XmlElement(name = "NbOfTxs")
	private Integer NbOfTxs;
	@XmlElement(name = "InitgPty")
	private InitgPty InitgPty;
}
@Data
@Accessors(chain = true)
@XmlAccessorType(XmlAccessType.FIELD)
class InitgPty {
	@XmlElement(name = "Nm")
	private String Nm;
}